package com.learning.springmvc.advance.valid.validator;

import com.learning.springmvc.advance.valid.bean.User;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * ClassName: UserLoginValidator
 * Description: 自定义校验。可以通过databind参数绑定，但是会覆盖springmvc 框架的实现
 * Date: 2019/5/22 13:57 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class UserLoginValidator implements Validator {

    private static final int MINIMUM_PASSWORD_LENGTH = 6;

    @Override
    public boolean supports(Class clazz) {
        return User.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name不能为空");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "mobile", "mobile不能为空");
        User login = (User) target;
        if (login.getMobile() != null && login.getMobile().trim().length() < MINIMUM_PASSWORD_LENGTH) {
            errors.rejectValue("mobile", "mobile 最小长度",
                    new Object[]{Integer.valueOf(MINIMUM_PASSWORD_LENGTH)},
                    "The mobile must be at least [" + MINIMUM_PASSWORD_LENGTH + "] characters in length.");
        }
    }

}
